package one.stand.service.impl;

import com.jmp.base.*;
import com.jmp.base.dto.*;
import com.jmp.feign.DynamicFeign;
import com.jmp.feign.MessageFeign;
import com.jmp.feign.TemplateFeign;
import lombok.extern.slf4j.Slf4j;
import one.stand.mapper.ArticleMapperExt;
import one.stand.model.ArticleWithBLOBs;
import one.stand.service.ArticleService;
import one.stand.service.sys.UserContentService;
import one.stand.util.OneListUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapperExt articleMapperExt;
    @Autowired
    private UserContentService userContentService;
    @Autowired
    private MessageFeign messageFeign;
    @Autowired
    private DynamicFeign dynamicFeign;
    @Autowired
    private TemplateFeign templateFeign;

    @Override
    @Transactional
    public void save(ArticleWithBLOBs article) {
        article.setStatus(null);
        article.setLabels(null);
        article.setPosition(null);
        article.setIsPush(null);
        article.setUpdateTime(null);
        article.setContent(setWidth100(article.getContent()));
        article.setAdContent(setWidth100(article.getAdContent()));
        if (Objects.nonNull(article.getId())) {
            articleMapperExt.updateByPrimaryKeySelective(article);

            // update dynamic
            DynamicUpdateByRelateRequest updateByRelateRequest = DynamicUpdateByRelateRequest.builder()
                    .relateType(DynamicApi.RELATE_ID_ARTICLE)
                    .relateId(article.getId())
                    .title(article.getTitle())
                    .details(article.getContent())
                    .photos(article.getShareCard())
                    .build();
            dynamicFeign.updateByRelate(updateByRelateRequest);

            // remove template
            TemplateRemoveArticleRequest removeArticleRequest = TemplateRemoveArticleRequest.builder()
                    .articleId(article.getId())
                    .build();
            templateFeign.removeArticle(removeArticleRequest);
        } else {
            articleMapperExt.insertSelective(article);
        }
    }

    @Override
    public void updateStatus(Integer id, Integer status, String labels, Integer position, Integer isPush) {
        ArticleWithBLOBs article = new ArticleWithBLOBs();
        article.setId(id);
        article.setStatus(status);
        if (status == ArticleApi.STATUS_UP) {
            article.setLabels(StringUtils.defaultIfBlank(labels, ArticleApi.DEFAULT_LABELS));
            article.setPosition(Objects.nonNull(position) ? position : ArticleApi.POSITION_INDEX);
            article.setIsPush(Objects.nonNull(isPush) ? isPush : ArticleApi.PUSH_NO);
            article.setUpTime(new Date());
        }
        articleMapperExt.updateByPrimaryKeySelective(article);

        // relate content
        if (status == ArticleApi.STATUS_UP) {
            article = articleMapperExt.selectByPrimaryKey(id);
            boolean isSelf = !ArticleApi.DEFAULT_COMPANYID.equals(article.getCompanyId());
            if (!isSelf) {
                userContentService.add(UserContentService.TYPE_ARTICLE, id, labels, UserContentService.TYPE_COMPANY);
            }

            // push
            if (Objects.nonNull(article.getIsPush()) && article.getIsPush() == ArticleApi.PUSH_YES) {
                if (StringUtils.isNoneBlank(labels)) {//推送标签-企业
                    MessagePushRequest pushRequest = MessagePushRequest.builder()
                            .type(MessagePushType.ARTICLE_UP)
                            .toType(MessageApi.TYPE_LABELS_COMPANY)
                            .toIds(OneListUtil.toList(labels, Integer::valueOf))
                            .title(article.getTitle())
                            .fillData(new String[]{article.getSubtitle()})
                            .pageParams(new Object[]{article.getId()})
                            .build();
                    messageFeign.push(pushRequest);
                } else if (isSelf) {//推送-企业自己
                    MessagePushRequest pushRequest = MessagePushRequest.builder()
                            .type(MessagePushType.ARTICLE_UP)
                            .toType(MessageApi.TYPE_COMPANY)
                            .toId(article.getCompanyId())
                            .title(article.getTitle())
                            .fillData(new String[]{article.getSubtitle()})
                            .pageParams(new Object[]{article.getId()})
                            .build();
                    messageFeign.push(pushRequest);
                } else {//推送所有
                    MessagePushRequest pushRequest = MessagePushRequest.builder()
                            .type(MessagePushType.ARTICLE_UP)
                            .toType(MessageApi.TYPE_ALL)
                            .title(article.getTitle())
                            .fillData(new String[]{article.getSubtitle()})
                            .pageParams(new Object[]{article.getId()})
                            .build();
                    messageFeign.push(pushRequest);
                }
            }
        } else {
            userContentService.remove(UserContentService.TYPE_ARTICLE, id);

            DynamicDeleteRelateRequest dynamicDeleteRelateRequest = DynamicDeleteRelateRequest.builder()
                    .relateType(DynamicApi.RELATE_ID_ARTICLE)
                    .relateId(id)
                    .build();
            dynamicFeign.deleteByRelate(dynamicDeleteRelateRequest);
        }
    }

    @Override
    @Transactional
    public void updatePosition(Integer id, Integer position) {
        ArticleWithBLOBs article = new ArticleWithBLOBs();
        article.setId(id);
        article.setPosition(Objects.nonNull(position) ? position : ArticleApi.POSITION_INDEX);
        articleMapperExt.updateByPrimaryKeySelective(article);
    }

    private String setWidth100(String html) {
        if (StringUtils.isBlank(html)) return StringUtils.EMPTY;

        String htmlResult = html.replaceAll("<img style=\"width:100%;", "<img style=\"");
        htmlResult = htmlResult.replaceAll("<img style=\"", "<img style=\"width:100%;");
        htmlResult = htmlResult.replaceAll("<img", "<img style=\"width:100%\"");
        return htmlResult;
    }
}
